<!-- 支付结果页 -->
<template>
  <view class="success-page">
    <view class="success-box u-flex-col u-row-center u-col-center">
      <image class="pay-img" :src="payImg[payState]" mode=""></image>
      <text class="notice">{{ payText[payState] }}</text>
      <text class="pay-money" v-if="payState === 'success' && orderDetail.total_fee">￥{{ orderDetail.total_fee }}</text>
      <view class="btn-box u-flex u-row-between">
        <block
          v-if="payState === 'success' && orderDetail.activity_type === 'groupon' && orderDetail.ext_arr.buy_type === 'groupon'">
          <button class="u-reset-button base-btn" v-if="orderDetail.ext_arr.groupon_id > 0"
            @tap="$Router.replace({ path: '/pages/activity/groupon/detail', query: { id: orderDetail.ext_arr.groupon_id } })">
            拼购详情
          </button>
          <button class="u-reset-button base-btn" v-else
            @tap="$Router.push('/pages/activity/groupon/my-groupon')">我的拼购</button>
        </block>

        <button class="u-reset-button base-btn" :style="type == 'group'? 'width:100%' :''"
          @tap="$Router.pushTab('/pages/index/index')">返回首页</button>
        <button class="u-reset-button base-btn u-m-l-10 u-m-r-10" v-if="type == 'goods'"
          @tap="$Router.replace({ path: '/pages/order/detail', query: { id: $Route.query.orderId } })">查看订单</button>
        <!-- <button class="u-reset-button base-btn" v-if="type == 'group'"
          @tap="$Router.pushTab('/pages/activity/groupon/my-groupon')">我的拼购</button> -->
        <button class="u-reset-button again-pay " v-show="payState === 'fail'" @tap="onPay">重新支付</button>
      </view>
    </view>
    <!-- <button @click="open()">打开弹窗</button> -->
    <uni-popup ref="pop" :mask-click="false">
      <my-turntable-draw ref="raffleWheel" :width="boxData.width" :text_show="text_show" :height="boxData.height" :prizeList="prizeList"
        :targetIndex="targetIndex" @befoterClick="befoterClick" @afterClick="afterClick">
      </my-turntable-draw>
      <view style="width: 100%;height: 500rpx;position: absolute;top: 0;left: 0;"></view>
      <view class="popup_close" @click="close()">
        <u-icon name="close"></u-icon>
      </view>
    </uni-popup>
    <!-- 登录提示 -->
    <shopro-auth-modal></shopro-auth-modal>
    <!-- modal -->
    <!-- #ifdef MP-WEIXIN -->
    <u-modal v-if="payState === 'success'" ref="uModal" v-model="showModal" :show-cancel-button="true"
      confirm-color="#FA6E3F" cancel-color="#666666" @confirm="onConfirm" confirm-text="订阅消息" cancel-text="取消"
      content="是否订阅消息,追踪订单信息?" title="提示"></u-modal>
    <!-- #endif -->
  </view>
</template>

<script>
  const innerAudioContext = uni.createInnerAudioContext();
  import myTurntableDraw from '@/components/my-turntable-draw/my-turntable-draw';
  import Pay from '@/shopro/pay';
  import {
    mapMutations,
    mapActions,
    mapState
  } from 'vuex';
  let payTimer = null;
  const payCount = 5;
  export default {
    components: {
      myTurntableDraw
    },
    data() {
      return {
        showModal: false,
        templateIds: [],
        wxOpenTags: '',
        orderDetail: {}, //订单详情
        payText: {
          fail: '支付失败',
          success: '支付成功',
          paying: '查询中...'
        },
		// 原来引用的是线上的地址 => 改成本地的
        // payImg: {
        //   fail: this.$IMG_URL + '/imgs/order/order_pay_fail.gif',
        //   success: this.$IMG_URL + '/imgs/order/order_pay_success.gif',
        //   paying: this.$IMG_URL + '/imgs/order/order_paying.gif'
        // },
		payImg: {
		  fail: this.$IMG_URL + '/imgs/order/order_pay_fail.gif',
		  success: '/static/images/order_pay_success.gif',
		  paying: this.$IMG_URL + '/imgs/order/order_paying.gif'
		},
        payState: '', //支付状态
        boxData: {
          width: 240,
          height: 240
        },
        is_open: false,
        text_show:false,
        prizeList: [{
            nickname: '',
            avatar: '../../../static/images/group/sc.png',
            mobile: '中奖'
          },
          {
            nickname: '',
            avatar: '../../../static/images/group/wsc.png',
            mobile: '红包'
          },
          {
            nickname: '',
            avatar: '../../../static/images/group/wsc.png',
            mobile: '红包'
          },
          {
            nickname: '',
            avatar: '../../../static/images/group/wsc.png',
            mobile: '红包'
          },
          {
            nickname: '',
            avatar: '../../../static/images/group/wsc.png',
            mobile: '红包'
          },
          {
            nickname: '',
            avatar: '../../../static/images/group/wsc.png',
            mobile: '红包'
          },
          {
            nickname: '',
            avatar: '../../../static/images/group/wsc.png',
            mobile: '红包'
          },
          {
            nickname: '',
            avatar: '../../../static/images/group/wsc.png',
            mobile: '红包'
          },
          {
            nickname: '',
            avatar: '../../../static/images/group/wsc.png',
            mobile: '红包'
          },
          {
            nickname: '',
            avatar: '../../../static/images/group/wsc.png',
            mobile: '红包'
          }
        ],
        targetIndex: 0,
        win_user: '',
        istrue: true,
        is_index: 0,
        type: 'goods'
      };
    },
    computed: {},
    onLoad() {
      let t = this;
      t.type = t.$Route.query.type;
	  console.log(t.$Route)
      t.payState = t.$Route.query.payState ? t.$Route.query.payState : '';
	  console.log(t.payState,t.payImg[t.payState])
      if (t.$Route.query.type == 'group') {
        uni.showLoading({
          title: '正在初始化拼购',
          success() {
            t.setpeople();
          }
        })
      }
    },
    onHide() {
      clearInterval(payTimer);
      payTimer = null;
      uni.hideLoading();
    },
    methods: {
      ...mapActions(['getCartList']),
      setpeople() {
        let that = this;
        // that.$http('goods.groupPeople', {
        //   group_id: that.$Route.query.orderId.group_id
        // }).then(res => {
        //   if (that.istrue) {
        that.$nextTick(() => {
          that.$refs.pop.open();
          // document.body.style.overflow = 'hidden';
        })
        //   }
        //   that.istrue = false;
        //   for (let x in res.data.group_user) {
        //     // this.prizeList[x] = res.data.group_user[x];
        //     that.$set(this.prizeList, x, res.data.group_user[x])
        //   }
        //   this.is_index = res.data.group_user.length;
        //   if (this.is_index == 10) {
        //     that.$nextTick(() => {
        uni.$emit('setView')
        //     })
        //   }
        //   // console.log(this.is_index,index)
        //   console.log(that.prizeList);
        //   that.win_user = res.data.win_user;
        //   if (res.data.group_user.length < 10) {
        //     setTimeout(function() {
        //       that.setpeople();
        //     }, 5000)
        //   } else if (res.data.group_user.length >= 10) {
        uni.hideLoading();
        setTimeout(function() {
          that.befoterClick();
        }, 500)
        //   }
        // })
      },
      // 订阅消息
      onConfirm() {
        //  #ifdef MP-WEIXIN
        this.templateIds.length &&
          uni.requestSubscribeMessage({
            tmplIds: this.templateIds,
            success: res => {
              console.log(res);
            },
            fail: err => {
              console.log(err);
            }
          });
        //  #endif
      },

      // 支付订单信息
      getOrderDetail() {
        let that = this;
        that.$http('order.detail', {
          id: that.$Route.query.orderId
        }).then(async res => {
          if (res.code === 1) {
            that.orderDetail = res.data;
            if (res.data.status > 0) {
              this.templateIds = await this.$store.dispatch('getMessageIds', this.orderDetail.activity_type ==
                'groupon' ? 'grouponResult' : 'result');
              this.showModal = this.templateIds.length;
            }
          }
        });
      },

      // 支付倒计时
      checkTimer() {
        let that = this;
        let count = 0;
        that.payState = 'paying';
        payTimer = setInterval(() => {
          count++;
          if (count < payCount) {
            that.checkPay();
          } else {
            clearInterval(payTimer);
            that.payState = 'fail';
          }
        }, 800);
      },

      // 检测支付
      async checkPay() {
        let that = this;
        let res = await that.$http(
          'order.detail', {
            id: that.$Route.query.orderId
          },
          false
        );
        if (res.code === 1 && res.data.status > 0) {
          that.payState = 'success';
          clearInterval(payTimer);
        }
      },

      // 重新支付
      onPay() {
        let that = this;
        let pay = new Pay(that.$Route.query.type, that.orderDetail);
      },
      open() {
        // 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
        this.$refs.pop.open();
      },
      close() {
        this.$refs.pop.close()
        // document.body.style.overflow = 'auto';
        clearInterval(this.cc)
      },
      befoterClick(data) {
        // console.log('开始抽奖', this.is_index)
        // console.log('开始抽奖')
        // 获取中奖单位下标
        // this.$http('goods.start', {
        //   group_id: this.$Route.query.orderId.group_id
        // }).then(res => {
        //   var _n;
        //   for (let x in this.prizeList) {
        //     if (this.prizeList[x].id == res.data) {
        //       _n = x;
        //     }
        //   }
        // this.win_user = res.data;
        // console.log(res,'拼购开奖');
        // console.log(this.prizeList)
        if (this.$Route.query.is_win != null && this.$Route.query.is_win == 1) {
          // console.log(this.$Route.query.is_win, '下表')
          this.targetIndex = parseInt(0)
          console.log(this._n, '下标');
          // data.callback && data.callback(_n)
          this.$refs.raffleWheel.rotoreAction(0);
          // this.$refs.raffleWheel.rotoreAction(_n)
        } else {
          // console.log(this.$Route.query.is_win, '下表')
          this._n = parseInt(Math.ceil(Math.random() * 1000000000 % 9));
          this.targetIndex = this._n;
          // data.callback && data.callback(_n)
          console.log(this._n, '下标');
          this.$refs.raffleWheel.rotoreAction(this._n);
          // this.$refs.raffleWheel.rotoreAction(_n)
        }

        // })
      },
      afterClick(data) {
        let that = this;
        if (data.type == 'end') {
          // console.log(data.content.count)
          // data.callback && data.callback()
          if (that.$Route.query.is_win == 1) {
            that.text_show = true;
            innerAudioContext.src = '../../../static/yes.mp3';
            innerAudioContext.play(() => {
              console.log('开始播放');
            });
            uni.showToast({
              title: '恭喜您拼中了！',
              icon: 'none',
              success() {
                // setTimeout(function() {
                // that.$nextTick(() => {
                //   that.$refs.pop.close();
                // })
                innerAudioContext.onEnded(() => {
                  uni.reLaunch({
                    url: '/pages/index/group'
                  })
                })
                // }, 1000)
              }
            })
          } else {
            that.text_show = false;
            innerAudioContext.src = '../../../static/no.mp3';
            innerAudioContext.play(() => {
              console.log('开始播放');
            });
            uni.showToast({
              title: '哇，拼不中也有红包哦！',
              icon: 'none',
              success() {
                // setTimeout(function() {
                // that.$nextTick(() => {
                //   that.$refs.pop.close();
                // })
                innerAudioContext.onEnded(() => {
                  uni.reLaunch({
                    url: '/pages/index/group'
                  })
                })

                // }, 2000)
              }
            })
          }
        }
      }
    }
  };
</script>

<style lang="scss" scopeds>
  html {
    overflow: hidden;
    position:fixed;
    height: 100%;
    margin: 0;
    padding: 0;
    border: none;
  }
  
  body {
    overflow: hidden;
    position: fixed;
    box-sizing: border-box;
    margin: 0;
    height: 100%;
  }
  .success-box {
    background: #fff;
    width: 750rpx;
    padding: 40rpx 0;

    .pay-img {
      width: 130rpx;
      height: 130rpx;
    }

    .notice {
      font-size: 30rpx;

      font-weight: bold;
      color: rgba(51, 51, 51, 1);
      line-height: 30rpx;
      margin-top: 30rpx;
    }

    .pay-money {
      font-size: 36rpx;
      color: #ff3000;
      font-weight: 600;
      margin-top: 20rpx;
    }

    .btn-box {
      margin-top: 30rpx;
      width: 660rpx;

      .base-btn {
        width: 320rpx;
        line-height: 70rpx;
        background: rgba(255, 255, 255, 1);
        border: 1rpx solid rgba(223, 223, 223, 0.5);
        border-radius: 35rpx;
        font-size: 28rpx;

        font-weight: 400;
        color: rgba(153, 153, 153, 1);
        padding: 0;
      }

      .again-pay {
        width: 320rpx;
        line-height: 70rpx;
        background: linear-gradient(90deg, #FA6E3F, #FEAB55);
        box-shadow: 0px 7rpx 6rpx 0px rgba(229, 138, 0, 0.22);
        border-radius: 35rpx;
        font-size: 28rpx;

        font-weight: 400;
        color: rgba(255, 255, 255, 0.8);
        padding: 0;
      }
    }
  }

  .hot-box {
    background: #fff;
    padding: 20rpx;
    margin-top: 20rpx;

    .hot-title {
      font-size: 30rpx;

      font-weight: 500;
      color: rgba(51, 51, 51, 1);
      height: 80rpx;
    }
  }

  .popup_close {
    width: 80rpx;
    height: 80rpx;
    border: 4rpx solid #fff;
    margin: auto;
    margin-top: 40rpx;
    border-radius: 50%;
    line-height: 72rpx;
    color: #ffffff;
    text-align: center;
  }
</style>
